<template>
  <div class="overview-container">
      <el-row :gutter="24" class="row1 clearfix">
        <el-col :lg="8" :md="24">
          <div class="box box-weather" :class="weatherObj.bg">
            <el-row :gutter="24">
              <el-col :span="14" class="weather-1">
                <div class="location" @click="showMap()">
                  <i class="iconfont icon-marker-site"></i>
                  {{weatherObj.city}}
                </div>
                <div class="info">
                  <div class="date marginbottom_10">{{weatherObj.date1}}</div>
                  <div class="weather clearfix">
                    <img class="weather" :src="weatherObj.img1"  width="60px">
                    <span>{{weatherObj.tmp1}}</span>
                  </div>
                </div>
              </el-col>
              <el-col :span="10">
                <el-row class="sub info">
                  <div class="date">{{weatherObj.date2}}</div>
                  <div class="weather clearfix">
                    <img class="weather" :src="weatherObj.img2" width="40px">
                    <span>{{weatherObj.tmp2}}</span>
                  </div>
                </el-row>
                <el-row class="sub info">
                  <div class="date">{{weatherObj.date3}}</div>
                  <div class="weather clearfix">
                    <!-- <i class="icon pull-left"></i> -->
                    <img class="weather" :src="weatherObj.img3" width="40px">
                    <span>{{weatherObj.tmp3}}</span>
                  </div>
                </el-row>
              </el-col>
            </el-row>
          </div>
        </el-col>
        <el-col :lg="16" :md="24">
          <div class="box box-countInfo">

            <el-row :gutter="24">
              <el-col :lg="12" :md="9" class="wrap">
                <div id="semicircleChart" class="semicircle">
                </div>
                <div class="semicircle-label inner">
                  <div class="value">
                    <span class="value">{{currentSize}}{{sizeUnit}}</span>
                  </div>
                  <div class="name">{{$t('index.powerNow')}}</div>
                </div>
                <div class="semicircle-label">
                  <span class="name">{{$t('vsite.capacityTotal')}}</span>
                  <span class="value">
                    <span class="value">{{systemSize}}{{sizeUnit}}</span>
                  </span>
                </div>
              </el-col>
              <el-col :lg="4" :md="5" class="count">
                <div class="name" :title="$t('overview.total_site')">{{$t('overview.total_site')}}</div>
                <div class="value">{{userInfo.siteCount||0}}</div>
              </el-col>
              <el-col :lg="4" :md="5" class="count">
                <div class="name" :title="$t('overview.total_inverter')">{{$t('overview.total_inverter')}}</div>
                <div class="value">{{userInfo.inverterCount||0}}</div>
              </el-col>
              <el-col :lg="4" :md="5" class="count">
                <div class="name" :title="$t('overview.online_inverter')">{{$t('overview.online_inverter')}}</div>
                <div class="value">{{userInfo.activeCount||0}}</div>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>
      
      <el-row :gutter="24" class="row">
        <el-col :lg="8" :md="24">
          <ul class="box box-info clearfix">
            <li class="day">
              <div class="name" :title="$t('overview.daily_generateElectricity')">{{$t('overview.daily_generateElectricity')}}</div>
              <i class="icon"></i>
              <div class="text">
                <span class="value">{{yieldObj.todayYield | numberFloatFrm(true) | getByIndex(0)}}</span>
                <span class="unit">{{yieldObj.todayYield | numberFloatFrm(true) | getByIndex(1)}}</span>
              </div>
            </li>
            <li class="month">
              <div class="name" :title="$t('overview.month_generateElectricity')">{{$t('overview.month_generateElectricity')}}</div>
              <i class="icon"></i>
             <div class="text">
                <span class="value">{{yieldObj.monthYield | numberFloatFrm(true) | getByIndex(0)}}</span>
                <span class="unit">{{yieldObj.monthYield | numberFloatFrm(true) | getByIndex(1)}}</span>
              </div>
            </li>
            <li class="year">
              <div class="name" :title="$t('overview.year_generateElectricity')">{{$t('overview.year_generateElectricity')}}</div>
              <i class="icon"></i>
              <div class="text">
                <span class="value">{{yieldObj.yearYield | numberFloatFrm(true) | getByIndex(0)}}</span>
                <span class="unit">{{yieldObj.yearYield | numberFloatFrm(true) | getByIndex(1)}}</span>
              </div>
            </li>
            <li class="total">
              <div class="name" :title="$t('overview.total_generateElectricity')">{{$t('overview.total_generateElectricity')}}</div>
              <i class="icon"></i>
              <div class="text">
                <span class="value">{{yieldObj.totalYield | numberFloatFrm(true) | getByIndex(0)}}</span>
                <span class="unit">{{yieldObj.totalYield | numberFloatFrm(true) | getByIndex(1)}}</span>
              </div>
            </li>
            <li class="money">
              <div class="name" :title="$t('overview.savingElectricity')">{{$t('overview.savingElectricity')}}</div>
              <i class="icon"></i>
              <div class="text">
                <span class="unit">{{electricity.currency}}</span>
                <span class="value">{{electricity.price | floatNum}}</span>
              </div>
            </li>
            <li class="co2">
              <div class="name" :title="$t('overview.CO2Reduction')">{{$t('overview.CO2Reduction')}}</div>
              <i class="icon"></i>
              <div class="text">
                <span class="value">{{yieldObj.totalYield | convertUnit('weight') | getByIndex(0)}}</span>
                <span class="unit">{{yieldObj.totalYield | convertUnit('weight') | getByIndex(1)}}</span>
              </div>
            </li>
          </ul>
        </el-col>
        
        
        <el-col :lg="16" :md="24">
          <div class="box box-group">
            <i class="el-icon-arrow-left el-icon--left control" @click="changeSite(-1)" v-show="siteIndex!=0"></i>
            <i class="el-icon-arrow-right el-icon--right control" @click="changeSite(1)" v-show="siteIndex!=siteIdArr.length-1"></i>
            <div class="wrap clearfix">
              <ul class="ul-info">
                <li>
                  <span class="name" :title="$t('device.inverter.siteName')">{{$t('device.inverter.siteName')}}</span>
                  <span class="value">
                    <!-- <router-link :to="{name:'overview_site', query:{ siteId: siteId,siteName:siteInfo.siteName }}" target="_blank" class="table-link">
                      {{siteInfo.siteName}}
                    </router-link> -->
                    <a href="javascript:;" class="table-link" @click="openRouter({path:'/overview_site', query:{ siteId: siteId,siteName:siteInfo.siteName }})">{{siteInfo.siteName}}</a>
                  </span>
                </li>
                <li>
                  <span class="name" :title="$t('vsite.capacity')">{{$t('vsite.capacity')}}</span>
                  <span class="value">{{siteInfo.ratedPower | num2}} kW</span>
                </li>
                <li>
                  <span class="name" :title="$t('vsite.inverterNum')">{{$t('vsite.inverterNum')}}</span>
                  <span class="value">{{siteInfo.inverterNum}}</span>
                </li>
                <li>
                  <span class="name" :title="$t('index.powerNow')">{{$t('index.powerNow')}}</span>
                  <span class="value">
                    {{siteInfo.gridPower/1000 | num2}} kW
                  </span>
                </li>
                <li>
                  <span class="name" :title="$t('overview.daily_generateElectricity')">{{$t('overview.daily_generateElectricity')}}</span>
                  <span class="value">
                    {{siteInfo.todayYield | numberFloatFrm(true) | getByIndex(0)}}
                    {{siteInfo.todayYield | numberFloatFrm(true) | getByIndex(1)}}
                  </span>
                </li>
                <li>
                  <span class="name" :title="$t('overview.total_generateElectricity')">{{$t('overview.total_generateElectricity')}}</span>
                  <span class="value">
                    {{siteInfo.totalYield | numberFloatFrm(true) | getByIndex(0)}}
                    {{siteInfo.totalYield | numberFloatFrm(true) | getByIndex(1)}}
                  </span>
                </li>
                
              </ul>
              <div class="chart-wrap">
                <div id="countChart" :style="{width: '150px', height: '150px'}"></div>
                <ul>
                  <li>
                    <div class="value">{{inverterStatus[1]}}</div>
                    <div class="name status1">{{$t('inverterStatus.status1')}}</div>
                  </li>
                  <li>
                    <div class="value">{{inverterStatus[4]}}</div>
                    <div class="name status4">{{$t('inverterStatus.status4')}}</div>
                  </li>
                  <li>
                    <div class="value">{{inverterStatus[2]}}</div>
                    <div class="name status2">{{$t('inverterStatus.status2')}}</div>
                  </li>
                  <li>
                    <div class="value">{{inverterStatus[3]}}</div>
                    <div class="name status3">{{$t('inverterStatus.status3')}}</div>
                  </li>
                </ul>
              </div>
            </div>
            <div class="clearfix">
              <el-radio-group v-model="dateType" @change="changeDate" size="mini" class="pull-right">
                <el-radio-button label="1">{{$t('overview.daily')}}</el-radio-button>
                <el-radio-button label="2">{{$t('overview.month')}}</el-radio-button>
                <el-radio-button label="3">{{$t('overview.year')}}</el-radio-button>
                <el-radio-button label="4">{{$t('all')}}</el-radio-button>
              </el-radio-group>
            </div>
            <!--功率曲线-->
            <div class="flex-item box-sale-bar">
              <div class="wrap-chart" :class="{active:dateType=='1'}">
                <div class="title">
                  {{$t('overview.gridPower')}}
                  <span class="time-group">
                    <button :class="{disabled:powerChartDate==currentDate}" @click="setDateVal(-1)"><i class="el-icon-arrow-left el-icon--left"></i></button>
                    <el-date-picker
                      v-model="powerChartDate"
                      type="date"
                      value-format="yyyy-MM-dd"
                      @change="initPowerChart()"
                      :clearable='false'
                      :picker-options="pickerOptions"
                      size="mini">
                    </el-date-picker>
                    <button :disabled="powerChartDate==currentDate" @click="setDateVal(1)"><i class="el-icon-arrow-right el-icon--right"></i></button>
                  </span>
                </div>
                <div id="powerChart" :style="{width: '100%', height: '200px'}"></div>
              </div>

              <div class="wrap-chart" :class="{active:dateType!='1'}">
                <div class="title flex-box-mian">
                  <!-- {{$t('overview.currentYield')}} -->
                  <el-select v-model="yeildType" size="mini" @change="initYieldChart(reportType)">
                    <el-option value='1' :label="$t('overview.currentYield')"></el-option>
                    <el-option value='2' :label="$t('overview.used')"></el-option>
                  </el-select>
                  <el-date-picker
                    v-model="echartsMonth"
                    value-format="yyyy-MM"
                    type="month"
                    v-if='dateType == 2'
                    :picker-options="pickerOptionsMonth"
                    :clearable='false'
                    @change='initYieldChart("2")'
                    >
                  </el-date-picker>
                  <el-date-picker
                    v-model='echartsYear'
                    value-format="yyyy"
                    type="year"
                    v-if='dateType == 3'
                    :picker-options="pickerOptionsYear"
                    :clearable='false'
                    @change='initYieldChart("3")'
                    >
                  </el-date-picker>
                </div>
                
                <div echart id="yieldBarChart" :style="{width: '100%', height: '200px'}"></div>
              </div>
            </div>
            <!--发电量-->

          </div>
        </el-col>
       

      </el-row>
    
    <baseBaiduMap :mapData='mapData'></baseBaiduMap>
    <baseGoogleMap :mapData='mapData'></baseGoogleMap>
  </div>
</template>

<script>
import '@/utils/index.js'
import moment from 'moment'
import baseBaiduMap from '../../components/map/baseBaiduMap'
import baseGoogleMap from '../../components/map/baseGoogleMap'
let echarts = require('echarts/lib/echarts');
require('echarts/lib/chart/pie')

export default {
  components:{
    baseBaiduMap,
    baseGoogleMap
  },
  data(){
    let _dateTool = this
    return{
      markers:[],
      mapData:{
          width:'100%',
          height:'400px',
          zoom:5,
          center:{
              lng:130,
              lat:29
          },
          mapObj:{},//地图对象
          markers:[],//地图上所有的标记
          showType:'site'
      },
      siteIdArr:[],
      siteId:'',
      inverterStatus:{},
      userData:JSON.parse(sessionStorage.getItem('userObj')),
      dateType:'2',
      weatherObj:{},
      powerObj:{gridPower:0,ratedPower:0},
      currentSize:0,//当前功率
      systemSize:0,//总功率
      sizeUnit:'W',//功率单位 W和kW
      yieldObj:{todayYield:0,monthYield:0,yearYield:0,totalYield:0},
      electricity:{price:'',currency:''},//节约电费
      userPower:{},
      userInfo:{},
      siteInfo:{},
      siteIndex:[],
      powerChartDate:this.$options.filters['dateFormat'](new Date(),'YYYY-MM-DD'),
      reportType:'1',
      yeildType:'1',
      pieYield:0,
      pieConsumeEnergy:0,
      currentTime:this.$options.filters['dateFormat'](new Date()),
      currentDate:this.$options.filters['dateFormat'](new Date(),'YYYY-MM-DD'),
      day:this.$options.filters['dateFormat'](new Date(),'DD'),
      month:this.$options.filters['dateFormat'](new Date(),'MM'),
      year:this.$options.filters['dateFormat'](new Date(),'YYYY'),
      yearList:[],
      isActive:0,
      powerChart:{},
      yieldBarChart:{},
      pickerOptions:{ //禁用今天之后的时间
          disabledDate(time) {
              return time.getTime() > Date.now()
          }
      },
      pickerOptionsMonth:{ //禁用今天之后的时间
          disabledDate(time) {
              return time.getTime() > new Date( `${_dateTool.getLastMonth()}`).getTime() 
          }
      },
      pickerOptionsYear:{ //禁用今天之后的时间
          disabledDate(time) {
              return time.getTime() > new Date( `${_dateTool.getLastYear()}`).getTime()  || time.getTime() < new Date('2017')
          }
      },
      semicircleChart:{},//半圆图
      countChart:{},//饼图
      echartsMonth:moment().format('YYYY-MM'),
      echartsYear:moment().format('YYYY'),
      relayPowerFlag:false,
      feedInPowerFlag:false,
    }
  },
  mounted(){
    // for(let i=2017;i<=this.year;i++){
    //   this.yearList.push(i);
    // }
    if(!(localStorage.getItem('relayPowerFlag')) && localStorage.getItem('relayPowerFlag') !=='0'){
      localStorage.setItem('relayPowerFlag','0')
    }
    if(!(localStorage.getItem('feedInPowerFlag')) && localStorage.getItem('feedInPowerFlag') !=='0'){
      localStorage.setItem('feedInPowerFlag','0')
    }
    this.relayPowerFlag = localStorage.getItem('relayPowerFlag')
    this.feedInPowerFlag = localStorage.getItem('feedInPowerFlag')
    this.getUserAllSiteId()//
    this.getYeildyByUser();//获取当前发电量
    this.getUserInfoCount();//获取信息统计
    
    this.saveElectricityUser()//节约电费

    this.getPowerByUser();//获取当前功率
    this.yieldBarChart = echarts.init(document.getElementById('yieldBarChart'));
    this.powerChart = echarts.init(document.getElementById('powerChart'));
    this.semicircleChart = echarts.init(document.getElementById('semicircleChart'));
    this.countChart = echarts.init(document.getElementById('countChart'));

    // this.initSemicircleChart()
    // this.initCountChart()
    this.getMap()
    
    window.addEventListener('resize', () => {
      this.powerChart.resize();
      this.yieldBarChart.resize()
      
      this.semicircleChart.resize();
      this.countChart.resize();
    })
    document.addEventListener('click',this.toggleBox);
  },
  destroyed(){
    document.removeEventListener('click',this.toggleBox);
  },
  computed: {
    // dayList: function () {
    //   if(this.month==1||this.month==3||this.month==5||this.month==7||this.month==8||this.month==10||this.month==12) return 31;
    //   if(this.month==4||this.month==6||this.month==9||this.month==11) return 30;
    //   if(this.month==2&&this.year%4==0) return 29;
    //   if(this.month==2&&this.year%4!=0) return 28;
    // }
  },
  watch:{
    day(){
      this.initYieldChart(this.chartType,this.reportType);
    },
    month(){
      this.day=this.$options.filters['dateFormat'](new Date(),'DD');
      this.initYieldChart(this.chartType,this.reportType);
    },
    year(){
      this.day=this.$options.filters['dateFormat'](new Date(),'DD');
      this.initYieldChart(this.chartType,this.reportType);
    }
  },
  methods:{
    convertPowerUnit(num){
      console.log(num,'convertPowerUnit')
      num=num||0;
      if(this.powerObj.ratedPower<10){
        this.sizeUnit='W'
        return num.toFixed(2)
      }else{
        this.sizeUnit='kW'
        return (num/1000).toFixed(2)
      }
    },
    openRouter(params){
        let url=this.$router.resolve(params)
        window.open(url.href,'_blank')
    },
    dayList(month,year){
      month = parseInt(month)
      if(month==1||month==3||month==5||month==7||month==8||month==10||month==12) return 31;
      if(month==4||month==6||month==9||month==11) return 30;
      if(month==2&&year%4==0) return 29;
      if(month==2&&year%4!=0) return 28;
    },
    getLastMonth(){//获取上个月日期 格式 2020-12
      var date = new Date; 
      var year = date.getFullYear();
      var month = date.getMonth();
      if(month == 0){
          year = year -1;
          month = 12; 
      }
      month += 1
      month = month < 10 ? `0${month}` : month
      return year+"-"+month;
    },
    getLastYear(){//获取上个月日期 格式 2020-12
      var date = new Date; 
      var year = date.getFullYear();
      return year
    },
    changeDate(val){
      if(val=='1'){
        this.initPowerChart();//功率曲线
      }else{
        this.initYieldChart(val);//发电量
      }
    },
    changeSite(val){
      this.siteIndex=this.siteIndex+val
      this.siteId=this.siteIdArr[this.siteIndex]
      this.initSiteData()
    },
    initSiteData(){
      this.getWeather();//获取天气
      this.getSiteInfo()
      this.getInverterStatesBySiteId()
      this.changeDate(this.dateType)
    },
    async getUserAllSiteId(){
      let res= await this.API.getUserAllSiteId({
        userId:this.userData.ids
      })
      if(res){
        console.log(res,'电站ids')
        this.siteIdArr=res
        this.siteIndex=0
        this.siteId=res[0]
        this.initSiteData()//刷新电站数据
      }
    },
    async saveElectricityUser(){
      let res= await this.API.saveElectricityUser({
        userId:this.userData.ids
      })
      if(res){
        this.electricity=res
        console.log(res,'节约电费')
      }
    },
    async getInverterStatesBySiteId(){
      let res= await this.API.getInverterStatesBySiteId({
        siteId:this.siteId
      })
      if(res){
        this.inverterStatus=res
        let data=[
            {value: res[1], name: this.$t('inverterStatus.status1')},
            {value: res[4], name: this.$t('inverterStatus.status4')},
            {value: res[2], name: this.$t('inverterStatus.status2')},
            {value: res[3], name: this.$t('inverterStatus.status3')},
        ]
        if(res[1]==0&&res[4]==0&&res[2]==0&&res[3]==0){
          this.initCountChart([{},{},{},{value:1,name:''}],false)
        }else{
          this.initCountChart(data)
        }
      }
    },
    
    async getSiteInfo(){
      let res= await this.API.getSiteInfoNew({
        siteId:this.siteId
      })
      if(res){
        this.siteInfo=res
      }
      console.log(res,'电站信息')
    },
    //半圆图
    initSemicircleChart(ratedPower,gridpower){

      var option = {
        grid: {
          left: "0",
          right: "0",
          bottom: "2%",
          containLabel: true
        },
        series: [
          {
            name: "一般",
            type: "pie",
            //起始刻度的角度，默认为 90 度，即圆心的正上方。0 度为圆心的正右方。
            startAngle: 0,
            hoverAnimation: false,
            tooltip: {},
            radius: ["100%", "75%"],
            center: ["50%", "60%"],
            labelLine: {
              normal: {
                show: false
              }
            },
            data: [
              {
                value: ratedPower,
                itemStyle: {
                  normal: {
                    color: "rgba(80,150,224,0)"
                  }
                }
              },
              {
                value: gridpower,  // 渐变色部分
                itemStyle: {
                  color:'#ffc835'
                  // color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  //   { offset: 0, color: "#FFDE00" },
                  //   { offset: 0.5, color: "#00ECD9" },
                  //   { offset: 1, color: "#00ECD9" }
                  // ])
                },
              },
              {
                value: ratedPower-gridpower, // 右侧部分
                itemStyle: {
                  normal: {
                    color: "#ccc"
                  }
                }
              }
            ]
          }
        ]
      }
      this.semicircleChart.setOption(option)
    },
    //饼图 在线数量
    initCountChart(data,flag=true){
      var option = {
        tooltip: {
            show:flag,//都为0时不显示
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
        },
        color:['#7bc594','#fdd001','#ef708b','#bdbdbd'],
        series: [
            {
                type: 'pie',
                radius: ['55%', '85%'],
                avoidLabelOverlap: false,
                label: {
                    show: false,
                    position: 'center'
                },
                // emphasis: {
                //     label: {
                //         show: true,
                //         fontSize: '30',
                //         fontWeight: 'bold'
                //     }
                // },
                labelLine: {
                    show: false
                },
                data: data
            }
        ]
      };
      this.countChart.setOption(option)
    },

    //切换时间
    setDateVal(append){
      this.powerChartDate=this.UtilsFun.setReportDate(this.powerChartDate,append);
      this.initPowerChart();
    },
    toggleBox(index){
      index=index!=0?index:0;
      if(index==0) console.log(index);
      if (this.isActive==index) {
        this.isActive=0;
      }else{
        this.isActive=index;
      }
    },
    forEachYield(res,i,xAxisData,yAxisData,g_data,d_data,c_data,eps_data){
      let flag=true;
      res.forEach(item=>{
        if(item.time==i){
          xAxisData.push(item.time);
          if(item.yieldtoday!=null){
            if(item.yieldtoday<=0){
              yAxisData.push(0.00);
            }else{
              yAxisData.push(item.yieldtoday.toFixed(2));
            }
          }else{
            yAxisData.push('-');
          }
          
          if(item.feedinenergy!=null){
						if(item.feedinenergy<=0){
							g_data.push(0.00);
						}else if(item.yieldtoday>=0 && item.yieldtoday<item.feedinenergy){
							//处理并网电量大于发电量时   并网电量显示发电量
							g_data.push(item.yieldtoday.toFixed(2));
						}else{
							g_data.push(item.feedinenergy.toFixed(2));
						}
					}else{
						g_data.push('-');
          }
          
          if(item.yieldtoday!=null && item.feedinenergy!=null){
						if(item.yieldtoday-item.feedinenergy<=0){
							d_data.push(0.00);
						}else{
							d_data.push((item.yieldtoday-item.feedinenergy).toFixed(2));
						}
					}else{
						d_data.push('-');
          }
          
          if(item.consumeenergy!=null){
						if(item.consumeenergy<=0){
							c_data.push(0.00);
						}else{
							c_data.push(item.consumeenergy.toFixed(2));
						}
					}else{
						c_data.push('-');
          }
          
          if(item.epsEnergy!=null){
						if(item.epsEnergy<=0){
							eps_data.push(0.00);
						}else{
							eps_data.push(item.epsEnergy.toFixed(2));
						}
					}else{
						eps_data.push('-');
					}
          flag=false;
        }
      })
      if (flag) {
				xAxisData.push(i);
				yAxisData.push('-');
				g_data.push('-');
				d_data.push('-');
				c_data.push('-');
				eps_data.push('-');
			}
    },
    async getYeildyByUser(){
      let res=await this.API.getYeildyByUser({
        currentTime: this.currentTime
      })
      this.yieldObj=res;
      console.log(this.yieldObj.monthYield);
    },
    async getUserInfoCount(){
      let res = await this.API.getUserInfoCount({
        userId: this.userData.ids
      })
      console.log(res,'userinfo')
      this.userInfo=res;
    },
    async getPowerByUser(){
      let res = await this.API.getPowerByUser({
        currentTime: this.currentTime
      })
      console.log(res,'安装容量  功率')
      this.powerObj=res;
      this.currentSize = this.convertPowerUnit(this.powerObj.gridPower)
      this.systemSize = this.convertPowerUnit(this.powerObj.ratedPower*1000)

      if(this.powerObj.ratedPower>0){
        if(this.powerObj.ratedPower*1000<this.powerObj.gridPower){
          this.initSemicircleChart(1,1)
        }else{
          this.initSemicircleChart(this.systemSize,this.currentSize)
        }
      }else{
        this.initSemicircleChart(1,0)
      }
    },
    //获取天气
    async getWeather(){
      let res = await this.API.getSunBySite({
        id: this.siteId
      })
      console.log(res,'天气')
      
      if(res){
        this.weatherObj={
          // city:(res.cnty||'') +' '+ (res.city||''),
          city:res.city||res.cnty||'',
          date1:res.date,
          img1:res.coded,
          tmp1:res.tmpMin?res.tmpMin+' ~ '+res.tmpMax+'℃':'',
        }
        let code=0;
        if(res.coded){
          code=Number(res.coded);
        }
        if(code==100||code==103||code==104){
          this.weatherObj.bg='sunny'
        }else if(code==101||code==102||code==153){
          this.weatherObj.bg='cloudy'
        }else if(code>=300&&code<=318){
          this.weatherObj.bg='rainy'
        }else if((code>=400&&code<=410)||code==499){
          this.weatherObj.bg='snowy'
        }else{
          this.weatherObj.bg='other'
        }
        //nextDayWeathers  未来两天天气
        let nextDay=res.nextDayWeathers?res.nextDayWeathers:[]
        let nextDayObj={}
        if(nextDay.length>0){
          nextDayObj={
            date2:nextDay[0].date,
            img2:nextDay[0].coded,
            tmp2:nextDay[0].tmpMin?nextDay[0].tmpMin+' ~ '+nextDay[0].tmpMax+'℃':'',
            date3:nextDay[1].date,
            img3:nextDay[1].coded,
            tmp3:nextDay[1].tmpMin?nextDay[1].tmpMin+' ~ '+nextDay[1].tmpMax+'℃':''
          }
        }else{
          nextDayObj={
            date2:'',
            img2:'',
            tmp2:'',
            date3:'',
            img3:'',
            tmp3:''
          }
        }
        this.weatherObj=Object.assign(this.weatherObj, nextDayObj);

        this.weatherObj.img1=res.coded?require('../../assets/img/weather/'+res.coded+'.png'):'';
        if(nextDay.length>0){
          this.weatherObj.img2=nextDay[0].coded?require('../../assets/img/weather/'+nextDay[0].coded+'.png'):'';
          this.weatherObj.img3=nextDay[1].coded?require('../../assets/img/weather/'+nextDay[1].coded+'.png'):'';
        }
        if(res.date){
          var startTime=new Date(res.date.replace(/-/g,'/')+' '+res.sr+':00').getTime();//开始时间
          var endTime=new Date(res.date.replace(/-/g,'/')+' '+res.ss+':00').getTime();//结束时间
          var date = res.nowUtcTime?new Date(res.nowUtcTime):new Date();
          if(!(date>startTime && date<endTime)){
            this.weatherObj.img1=res.coden?require('../../assets/img/weather/'+res.coden+'.png'):'';
            // if(nextDay.length>0){
            //   this.weatherObj.img2=nextDay[0].coden?require('../../assets/img/weather/'+nextDay[0].coden+'.png'):'';
            //   this.weatherObj.img3=nextDay[1].coden?require('../../assets/img/weather/'+nextDay[1].coden+'.png'):'';
            // }
          }
        }

      }
    },

    //电量统计
    async initYieldChart(reportType){
      this.reportType=reportType;
      var dateTime='';
      let m = this.month>9?this.month:"0"+this.month;//获取当前月份的日期
      let d = this.day>9?this.day:"0"+this.day;
      if(this.reportType==1) dateTime=this.year+'-'+m+'-'+d
      if(this.reportType==2) dateTime=this.year+'-'+m
      if(this.reportType==3) dateTime=this.year


        let res = await this.API.getYeildyChartBySite({
          siteId:this.siteId,
          reportType : reportType,
          day : this.day,
          month : reportType == 2 ?this.echartsMonth.split('-')[1]:this.month,
          year : reportType == 2 ?this.echartsMonth.split('-')[0]:this.echartsYear,
          webTime : this.$options.filters['dateFormat'](new Date(),'YYYY,MM,DD')
        })

        let resData=res.returnList;//数据
        let maxTick=res.max;//最大刻度

        let xAxisData=[],yAxisData=[],g_data=[],d_data=[],c_data=[],eps_data=[];
        let array_data1=[],array_data2=[],array_data3=[],array_data4=[];
        let theMax1=0,theMax2=0,theMax3=0,theMax4=0;//最大值
        let _this=this;
        let unit_time='';

        if(resData!=null && resData.length>0){
          resData.forEach(item=>{
            array_data1.push(item.yieldtoday<0?0:item.yieldtoday);
            array_data2.push(item.feedinenergy<0?0:item.feedinenergy);
            if(item.yieldtoday!=null && item.feedinenergy!=null){
              array_data3.push(item.yieldtoday-item.feedinenergy<0?0:(item.yieldtoday-item.feedinenergy));
            }else{
              array_data3.push(null);
            }
            array_data4.push(item.consumeenergy<0?0:item.consumeenergy);//耗电量
          })
          theMax1=(this.$options.filters['MaxNum'](array_data1)/10000).toFixed(2);
          theMax2=(this.$options.filters['MaxNum'](array_data2)/10000).toFixed(2);
          theMax3=(this.$options.filters['MaxNum'](array_data3)/10000).toFixed(2);
          theMax4=(this.$options.filters['MaxNum'](array_data4)/10000).toFixed(2);//耗电量
        }
        let dayList = this.dayList(this.echartsMonth.split('-')[1],this.echartsMonth.split('-')[0])
          //根据日期类型初始化数据
          if(reportType==1){
            unit_time=this.$t('index.unitTimeHour');
            let hour=23;
            for(let i=0;i<=hour;i++){
              this.forEachYield(resData,i,xAxisData,yAxisData,g_data,d_data,c_data,eps_data);
            }
          }else if(reportType==2){
            unit_time=this.$t('index.unitTimeDay');
            for(let i=1;i<=dayList;i++){
              this.forEachYield(resData,i,xAxisData,yAxisData,g_data,d_data,c_data,eps_data);
            }
          }else if(reportType==3){
            unit_time=this.$t('index.unitTimeMonth');
            for(let i=1;i<=12;i++){
              this.forEachYield(resData,i,xAxisData,yAxisData,g_data,d_data,c_data,eps_data);
            }
          }else if(reportType==4){
            unit_time=this.$t('index.unitTimeYear');
            let temp;
            for(var i=0; i < resData.length; i++){
              for(var j=0; j < resData.length-i-1; j++){
                if(resData[j].time>resData[j+1].time){
                  temp=resData[j];
                  resData[j]=resData[j+1];
                  resData[j+1]=temp;
                }
              }             
            }

            resData.forEach(item=>{
              xAxisData.push(item.time);
              if(item.yieldtoday!=null){
                if(item.yieldtoday<=0){
                  yAxisData.push(0.00);
                }else{
                  yAxisData.push(item.yieldtoday.toFixed(2));
                }
              }else{
                yAxisData.push('-');
              }
              
              if(item.feedinenergy!=null){
                if(item.feedinenergy<=0){
                  g_data.push(0.00);
                }else if(item.yieldtoday>=0 && item.yieldtoday<item.feedinenergy){
                  //处理并网电量大于发电量时   并网电量显示发电量
                  g_data.push(item.yieldtoday.toFixed(2));
                }else{
                  g_data.push(item.feedinenergy.toFixed(2));
                }
              }else{
                g_data.push('-');
              }
              
              if(item.yieldtoday!=null && item.feedinenergy!=null){
                if(item.yieldtoday-item.feedinenergy<=0){
                  d_data.push(0.00);
                }else{
                  d_data.push((item.yieldtoday-item.feedinenergy).toFixed(2));
                }
              }else{
                d_data.push('-');
              }
              
              if(item.consumeenergy!=null){
                if(item.consumeenergy<=0){
                  c_data.push(0.00);
                }else{
                  c_data.push(item.consumeenergy.toFixed(2));
                }
              }else{
                c_data.push('-');
              }

              if(item.epsEnergy!=null){
                if(item.epsEnergy<=0){
                  eps_data.push(0.00);
                }else{
                  eps_data.push(item.epsEnergy.toFixed(2));
                }
              }else{
                eps_data.push('-');
              }
            })
          }

          let yeildData;
          if(this.yeildType=='1'){
            yeildData={name:this.$t('index.toGrid'),color:'#f4b600',data:g_data}
          }else if(this.yeildType=='2'){
            yeildData={name:this.$t('index.powerConsumption'),color:'#eb6206',data:c_data}
          }

          let optionObj={
            tooltip:{
              formatter: function (params) {
                if(params.length==0) return ""
                var text = _this.$options.filters['formatUnitTime'](unit_time,params[0]['axisValue'])+'<br>';
                if(params.length>0){
                  var params1=params[0]['data']=='-'?'-':parseFloat(params[0].data).toFixed(2);
                  text += params[0]['seriesName']+' : '+params1+'kWh<br>';
                }
                if(params.length>1){
                  var params2=params[1]['data']=='-'?'-':parseFloat(params[1].data).toFixed(2);
                  text += params[1]['seriesName']+' : '+params2+'kWh<br>';
                }
                if(params.length>2){
                  var params3=params[2]['data']=='-'?'-':parseFloat(params[2].data).toFixed(2);
                  text += params[2]['seriesName']+' : '+params3+'kWh<br>';
                }
                return text;
              }
            },
            legend:{
              // data:[
                  // {name : this.$t('index.directSelfUse'),icon : 'stack'},
                  // {name : yeildData.name,icon : 'stack'},
                  // {name : 'EPS电量',icon : 'stack'},
                // ]
            },
            xAxis:{
              name:'('+unit_time+')',
              data : xAxisData
            },
            yAxis:{
              name:'kWh'
            },
            grid : {
              left : '15px',
              top : '35px',
              right : '70px',
              bottom : '30px',
              containLabel :true
            },
            series : [
              this.EchartsUtil.getSeries({type:'bar',name:this.$t('index.directSelfUse'),barMaxWidth:20,stack:'one',color:'#6DA719',data:d_data}),
              this.EchartsUtil.getSeries({type:'bar',name:yeildData.name,barMaxWidth:20,stack:'one',color:yeildData.color,data:yeildData.data}),
              // this.EchartsUtil.getSeries({type:'bar',name:'EPS电量',barMaxWidth:20,stack:'one',color:'#6DA719',data:eps_data}),
            ]
          };
          this.yieldBarChart.setOption(this.EchartsUtil.getOption(optionObj));
    },
    //功率曲线
    async initPowerChart(){
      let res = await this.API.getSitePowerByUser({
        siteId:this.siteId,
        time: this.powerChartDate
      })
      let resData=res?res.object:[]
      //判断是否有其他设备功率
      let flag_other=false
      resData.forEach(item=>{
        if(item.feedinPowerMeter2){
          flag_other=true
        }
      })
      let siteAndOverOther=this.$t('overview.siteAndOver.other');
      let colorArray=['#f4b600','#72BC38','#C962F7','#eb6206'];
      if(flag_other){
        colorArray.unshift('#0DDEB2');
      }

      // let powerdc=0;//PV功率
      // let gridpower;//AC功率
      // let feedinpower;//并网功率
      // let batPower;//电池功率
      // let overOther//其他设备功率
      // let loadPower;//负载功率

      let times1=[],times2=[],times3=[],times4=[],times5=[],times6=[];
      resData.forEach(item=>{
        let powerdc=0;
        if(item.powerdc1){
          powerdc += item.powerdc1;
        }
        if(item.powerdc2){
          powerdc += item.powerdc2;
        }
        if(item.powerdc3){
          powerdc += item.powerdc3;
        }
        if(item.powerdc4){
          powerdc += item.powerdc4;
        }
        let time=new Date(Date.parse( (item.uploadTimeValue.replace(/-/g,"/")).replace(/\./g,"") )).getTime()
        times1.push([time,powerdc]);//pv功率
        times2.push([time,item.gridpower]);//AC功率
        times3.push([time,item.relayPower||0]);//负载
        times4.push([time,item.feedinpower]);//并网功率
        // times6.push([time,item.feedinPowerMeter2]);//其它功率
        // times5.push([time,item.batPower1]);//电池功率
      })

      var option = {
          color:colorArray,
          tooltip: {
              trigger: 'axis',
          },
          legend: {
            show : true,
            itemGap : 10,// 间距
            y : 'bottom',
            // data: [this.$t('index.solarPower'),this.$t('index.outPutPower'),this.$t('newoverView.relayPower'),this.$t('index.feedInPower')],
            textStyle : {
              color : '#68676C',
              fontSize : 12
            },
            selected:{}
          },
          grid : {
            left : '15px',
            top : '20px',
            right : '40px',
            bottom : '40px',
            containLabel :true
          },
          xAxis: {
              type: 'time',
              nameTextStyle:{
                color : '#68676C',
                fontSize:11
              },
              axisLine: {
                onZero: false,
                lineStyle:{
                  width:0
                }
              },
              axisTick : {
                inside : false
              },
              splitLine: {
                  show: false
              },
              axisLabel : {
                formatter: function(value,index){
                  var date = new Date(value);
                  var hour = date.getHours()<10?'0'+ date.getHours():date.getHours();
                  var minutes = date.getMinutes()<10?'0'+ date.getMinutes():date.getMinutes();
                  return hour+':'+minutes;
                },
                textStyle : {
                  color : '#68676C'
                }
              }
          },
          yAxis: {
              type: 'value',
              nameTextStyle: {
                color: '#777',
                fontSize: 12,
              },
              axisLine : {
                show : false
              },
              axisTick : {
                show : false
              },
              splitLine : {
                show : true,
                lineStyle : {
                  color : [ '#dbdbdc' ]
                }
              },
              axisLabel : {
                formatter: '{value} W',
                textStyle : {
                  color : '#68676C'
                }
              }
          },
          dataZoom: [{
              type: 'inside'
          }],
          series: [{
              name: this.$t('index.solarPower'),
              type: 'line',
              symbol: 'none',
              smooth : true,
              lineStyle:{
                width:1
              },
              areaStyle: {
                opacity:0.3
              },
              data:times1
          },{
              name: this.$t('index.outPutPower'),
              type: 'line',
              symbol: 'none',
              smooth : true,
              lineStyle:{
                width:1
              },
              areaStyle: {
                opacity:0.3
              },
              data:times2
          },{
              name: this.$t('newoverView.relayPower'),
              type: 'line',
              symbol: 'none',
              smooth : true,
              lineStyle:{
                width:1
              },
              areaStyle: {
                opacity:0.3
              },
              data:times3
          },{
              name: this.$t('index.feedInPower'),
              type: 'line',
              symbol: 'none',
              smooth : true,
              lineStyle:{
                width:1
              },
              areaStyle: {
                opacity:0.3
              },
              data:times4
          }]
      };
      this.$set( option.legend.selected,this.$t('newoverView.relayPower'),this.relayPowerFlag=='0'?false:true)
      this.$set( option.legend.selected,this.$t('index.feedInPower'),this.feedInPowerFlag=='0'?false:true)
      this.powerChart.setOption(option);
      let echartThat = this
      this.powerChart.on('legendselectchanged', function(params) {
        if(params.selected[echartThat.$t('newoverView.relayPower')]){
          localStorage.setItem('relayPowerFlag','1')
        }else{
          localStorage.setItem('relayPowerFlag','0')
        }
        if(params.selected[echartThat.$t('index.feedInPower')]){
          localStorage.setItem('feedInPowerFlag','1')
        }else{
          localStorage.setItem('feedInPowerFlag','0')
        }
      })
    },
    async getMap(){
      this.UtilsFun.createGoogle()
      let res = await this.API.getRoundSiteAddress()
      console.log(res,'------点')
      res.forEach(item=>{
        let pointType=localStorage.getItem('mapType')==1?'baidu':'google'
        var transParam = this.UtilsFun.transformPoint(item.latitude,item.longitude,pointType);
        this.mapData.markers.push({
          lng:Number(transParam.longitude),
          lat:Number(transParam.latitude),
          label:item.siteName
        })
      })
      this.mapData.center=this.mapData.markers[0]
      console.log(this.mapData.markers)

    },
    //打开地图
    showMap(){
      console.log(this.mapData.markers,'----------------------point')
      if(this.mapData.markers.length>0){
        if(localStorage.getItem('mapType')==1){
          this.$store.commit('setVisibleBaiduMap',true)
        }else{
          this.$store.commit('setVisibleGoogleMap',true)
        }
      }else{
        // this.$message.error('您未录入电站位置信息')
      }
    }
  }
}
</script>

<style lang="less" >
@color_box_bg:#EFEFEF;
@color_title:#444;
@color_text:#636162;
@color_unit:#636162;
@color_light:#ff8920;
@border_bottom:1px dashed #D1D1D1;
@border_radius:3px;
@color_unit:#8a8a8a;
// .el-container{
//   background: #efefef;
// }
.flex-box-mian{
  display: flex;
  justify-content: space-between;
}
.text-overflow(){
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
.overview-container{
  margin: -20px;
  background: #efefef;
  color: #3a4457;
  padding: 20px;
  height: 100%;
  overflow: auto;
  .row1{
    height: 270px;
  }
  .box{
    height: 100%;
    background: #fff;
    box-shadow: 4px 4px 5px rgba(0,0,0,.1);
    border-radius: 10px;
    overflow: hidden;
    &.box-weather{
      border-radius: 10px;
      height: 250px;
      overflow: hidden;
      &.sunny{
        background: url(../../assets/img/overview_new/sunny.png) no-repeat top center / cover;
      }
      &.cloudy,&.other{
        background: url(../../assets/img/overview_new/cloudy.png) no-repeat top center / cover;
      }
      &.rainy{
        background: url(../../assets/img/overview_new/rainy.png) no-repeat top center / cover;
      }
      &.snowy{
        background: url(../../assets/img/overview_new/snowy.png) no-repeat top center / cover;
      }
    
      .weather-1{
        height: 250px;
        border-right: 1px solid #d2d2d2;
        .location{
          height: 40%;
          padding: 20px;
          box-sizing: border-box;
          font-size: 20px;
          color: #fff;
          i{
            font-size: 24px;
          }
        }
        .info span{
          display: inline-block;
          width: calc(100% - 70px);
          text-align: center;
        }
      }
      .weather-2,.weather-3{
        height: 125px;
      }
      .info{
        font-size: 18px;
        color: #fff;
        padding: 10px;
        box-sizing: border-box;
        .date{
          font-size: 24px;
        }

        img{
          vertical-align: middle;
        }
        span{
          display: inline-block;
          font-size: 24px;
          vertical-align: middle;
          padding-left:10px;
        }
        &.sub{
          padding:20px 0;
          font-size: 14px;
          .date{
            margin-bottom: 20px;
            font-size: 20px;
          }
          span{
            font-size: 18px;
          }
          
        }

      }
    }

    &.box-countInfo{
      
      .wrap{
        position: relative;
        height: 250px;
        .semicircle{
          width: 100%;
          height: 270px;
        }
        .semicircle-label{
          position: absolute;
          top: 80%;
          left: 50%;
          transform: translate(-50%);
          width: 100%;
          text-align: center;
          .name{
            text-align: center;
          }
          .value{
            padding-left: 10px;
            font-size: 24px;
          }
          &.inner{
            top:40%;
            .value{
              font-size:24px;
            }
          }
        }
      }
      .count{
        margin: 65px 0;
        height: 120px;
        line-height: 60px;
        text-align: center;
        border-left:1px solid #c5c5c5;
        .name{
          font-weight: bold;
          .text-overflow()
        }
        .value{
          font-size: 20px;
        }
      }
    }

    &.box-info{
      height: 468px;
      li{
        width: 50%;
        float: left;
        padding: 5px;
        margin: 15px 0;
        box-sizing: border-box;
        text-align: center;
        border-right:1px solid #c5c5c5;
        .name{
          font-weight:bold;
          font-size: 14px;
          color:#a1a6ae;
          .text-overflow()
        }
        .icon{
          display: inline-block;
          background: url(../../assets/img/overview_new/icon/month.png) no-repeat;
          background-size:100% 100% !important;
          width:60px;
          height:60px;
          // margin: 0 auto;
        }
        .value{
          font-size: 25px;
        }
        &.day{
          i{
            background: url(../../assets/img/overview_new/icon/day.png) no-repeat;
          }
          .text{
            color:#dfca64;
          }
        }
        &.month{
          i{
            background: url(../../assets/img/overview_new/icon/month.png) no-repeat;
          }
          .text{
            color:#8dbb71;
          }
          border-right:none;
        }
        &.year{
          i{
            background: url(../../assets/img/overview_new/icon/year.png) no-repeat;
          }
          .text{
            color:#7486a1;
          }
        }
        &.total{
          i{
            background: url(../../assets/img/overview_new/icon/total.png) no-repeat;
          }
          .text{
            color:#9c84a6;
          }
          border-right:none;
        }
        &.money{
          i{
            background: url(../../assets/img/overview_new/icon/money.png) no-repeat;
          }
          .text{
            color:#7fc3b9;
          }
        }
        &.co2{
          i{
            background: url(../../assets/img/overview_new/icon/co2.png) no-repeat;
          }
          .text{
            color:#72b5c1;
          }
          border-right:none;
        }
      }

    }
    &.box-group{
      position: relative;
      padding: 10px 20px;
      .control{
        position:absolute;
        // width: 30px;
        // height:80px;
        top:48%;
        color:#aaa;
        font-size: 30px;
        cursor: pointer;
        &:hover{
          color: @color_light;
        }
        &.el-icon--left{
          left:0;
        }
        &.el-icon--right{
          right:0;
        }
      }
      .wrap{
        height: 150px;
        .ul-info{
          width: 40%;
          float: left;
          box-sizing: border-box;
          color: @color_unit;
          li{
            padding: 3px;
            box-sizing: border-box;
            font-size: 14px;
            .name{
              display: inline-block;
              width: calc(100% - 100px);
              .text-overflow()
            }
            .value{
              width: 100px;
              text-align: right;
              .text-overflow()
            }
          }
          .table-link{
            color: @color_unit;
            text-decoration: underline;
          }
          .value{
            float: right;
          }
        }
        .chart-wrap{
          width: 60%;
          float: left;
          #countChart{
            margin:0 20px;
            width:150px;
            height:150px;
            float: left;
            background: #fff;
          }
          ul{
            float: left;
            width: calc(100% - 190px);
            li{
              width:50%;
              float:left;
              text-align:center;
              padding: 10px 0;
              box-sizing: border-box;
              .name{
                position: relative;
                color:@color_unit;
                margin-top: 10px;
              }
              .name::before{
                content: '';
                position: absolute;
                top: 11px;
                transform: translate(-14px,-50%);
                width: 10px;
                height: 10px;
                border-radius: 10px;
              }
              .status1::before{
                background: #7bc594;
              }
              .status4::before{
                background: #fdd001;
              }
              .status2::before{
                background: #ef708b;
              }
              .status3::before{
                background: #bdbdbd;
              }
            }
          }
        }
      }
      
    }


    .flex-item{
      position: relative;
      margin: 10px 5px;
      height: 250px;
      background:@color_box_bg;
      border-radius: @border_radius;
      .title{
        padding: 0 10px;
        height: 40px;
        line-height: 40px;
        border-bottom: @border_bottom;
        color: @color_title;
      }

      .wrap-chart{
        position: absolute;
        width: 100%;
        height: max-content;
        top: 0;
        left: 0;
        background: #efefef;
        visibility: hidden;
        &.active{
          visibility:visible;
        }
      }
    }

    
  }

  .time-group{
      float: right;
      .el-input{
        width: 150px;
      }
      button{
        border:none;
        &:focus {
          outline: none;
        }
        &:not(:disabled):hover{
          cursor: pointer;
          color: @color_light;
        }
        i{
          line-height: 24px;
          font-weight: bold;
          font-size: 14px;
          
        }
      }
    }



}
</style>